package cn.com.gridinfo.sooc.core.expand.callname.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.core.expand.callname.bean.ClassInfo;
import cn.com.gridinfo.sooc.utils.widget.WheelDialog;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;
import cn.com.gridinfo.sooc.utils.widget.widget.adapters.AbstractWheelTextAdapter;
import cn.com.gridinfo.sooc.utils.widget.widget.views.OnWheelChangedListener;
import cn.com.gridinfo.sooc.utils.widget.widget.views.OnWheelScrollListener;
import cn.com.gridinfo.sooc.utils.widget.widget.views.WheelView;

/**
 * 创建课堂界面
 *
 * @author yingchunli
 */
public class CreateClassActivity extends BaseSoocActivity {

    @InjectView(R.id.className)
    ClearEditText className;//课堂名称
    @InjectView(R.id.selectCourse)
    ImageView selectCourseIcon;//选择课程的图标
    @InjectView(R.id.classTheme)
    ClearEditText classTheme;//课堂主题
    @InjectView(R.id.classAddress)
    ClearEditText classAddress;//上课地址
    @InjectView(R.id.classTime)
    TextView classTime;//上课时间
    @InjectView(R.id.skxq)
    TextView skxq;//上课学期
    @InjectView(R.id.paizhaoSign)
    CheckBox paizhaoSign;//拍照选择按钮
    @InjectView(R.id.commitbtn)
    Button commitBtn;//提交按钮
    CallNameDao dao;
    private WheelView wv;
    CourseListAdapter adapter;//适配器
    private List<String> list = new ArrayList<>();
    int currentPosition;//当前显示的item
    int selectPosition;//选择的item
    List<ClassInfo> courseList = new ArrayList<>();//该用户已创建过得课程列表
    String currentText;//当前选中文字

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.expand_callname_createclass);
        ButterKnife.inject(this);
        dao = new CallNameDao(this);
        dao.getClass(CodeConst.EXPAND_GET_CLASS);//创建课堂时获取课堂信息
        commitBtn.setEnabled(false);//设置提交按钮初始状态不能点击
        selectCourseIcon.setVisibility(View.GONE);//不显示选择课程的图标
        //按键完成监听
        classTheme.setImeOptions(EditorInfo.IME_ACTION_DONE);
//        classTheme.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            public boolean onEditorAction(TextView v, int actionId,
//                                          KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_DONE) {
//                    if (!StringUtils.isNull(className.getText().toString().trim())) {
//                        onClick();
//                    }
//                }
//                return false;
//            }
//        });
    }

    /**
     * 选择课程的点击
     */
    @OnClick(R.id.selectCourse)
    void onSelectCourseClick() {

        //展现课程列表，选择课程
        final List<String> list = new ArrayList<>();
        for (int i = 0; i < courseList.size(); i++)
            list.add(courseList.get(i).getKcmc());
        currentText = list.get(0);
        View wheelDialog = LayoutInflater.from(this).inflate(R.layout.wheel_dialog, null);
        wv = (WheelView) wheelDialog.findViewById(R.id.list_wheel);
        adapter = new CourseListAdapter(this, list, 0, 16, 14);
        selectPosition = 0;
        wv.setVisibleItems(3);
        wv.setViewAdapter(adapter);

        wv.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                currentText = (String) adapter.getItemText(wheel.getCurrentItem());
                selectPosition = wheel.getCurrentItem();
                setTextviewSize(currentText, adapter);
                currentPosition = wheel.getCurrentItem();
            }
        });
        wv.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                String currentText = (String) adapter.getItemText(wheel.getCurrentItem());
                setTextviewSize(currentText, adapter);
            }
        });
        new MaterialDialog.Builder(this)
                .title("选择课程名称")
                .titleColor(Color.BLACK)
                .customView(wheelDialog, true)
                .backgroundColor(Color.WHITE)
                .positiveColor(getResources().getColor(R.color.colorAccent))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                        className.setText(list.get(selectPosition));
                        className.requestFocus();
                        className.setSelection(className.getText().toString().length());
                    }
                })
                .cancelable(true)
                .positiveText(R.string.agree)
                .positiveColor(getResources().getColor(R.color.colorAccent))
                .show();
    }

    /**
     * 设置字体大小
     *
     * @param curriteItemText
     * @param adapter
     */
    public void setTextviewSize(String curriteItemText, CourseListAdapter adapter) {
        List<View> arrayList = adapter.getTestViews();
        int size = arrayList.size();
        String currentText;
        for (int i = 0; i < size; i++) {
            TextView textview = (TextView) arrayList.get(i);
            currentText = textview.getText().toString();
            if (curriteItemText.equals(currentText)) {
                textview.setTextSize(16);
                textview.setTextColor(getResources().getColor(R.color.color_tv333));
            } else {
                textview.setTextSize(14);
                textview.setTextColor(getResources().getColor(R.color.color_999));
            }
        }
    }

    /**
     * 判断必填内容是否为空，确定注册按钮处于什么状态
     * 当必填内容全不为空时，提交 按钮才处于可点击状态，否则，不可点击
     */
    @OnTextChanged(value = {R.id.classAddress, R.id.className, R.id.classTheme}, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        if (className.getText().toString().trim().equals("") || classTheme.getText().toString().trim().equals("")) {
            commitBtn.setEnabled(false);
        } else {
            commitBtn.setEnabled(true);
        }
    }

    /**
     * 提交按钮的点击
     */
    @OnClick(R.id.commitbtn)
    void onClick() {
        String kcmc = className.getText().toString().trim();
        String ktzt = classTheme.getText().toString().trim();
        String skdd = classAddress.getText().toString().trim();
        String pzqd;
        if (paizhaoSign.isChecked()) {
            pzqd = "1";//拍照签到
        } else {
            pzqd = "0";//不拍照签到
        }
        //提交创建课堂的请求
        dao.createClass(kcmc, ktzt, skdd, pzqd, CodeConst.EXPAND_CREATE_CLASS);
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            switch (requestCode) {
                //获取创建课堂的信息
                case CodeConst.EXPAND_GET_CLASS:

                    if (dao.getClassInfo().getSckcm().equals("")) {
                        //第一次创建课堂
                        className.setHint("请输入课程");
                        classTheme.setHint("请输入课堂主题");
                        classAddress.setHint("可选填");
                        selectCourseIcon.setVisibility(View.GONE);//不显示选择课程的图标
                    } else {
                        selectCourseIcon.setVisibility(View.VISIBLE);//显示选择课程的图标
                        className.setText(dao.getClassInfo().getSckcm());//显示上次上课名称
                        //设置光标位置
                        className.setSelection(dao.getClassInfo().getSckcm().length());
                    }
                    if (dao.getMyclasses().size() > 0) {
                        selectCourseIcon.setVisibility(View.VISIBLE);//显示选择课程的图标
                        courseList.addAll(dao.getMyclasses());//该教师创建过的课程
                    }
                    classTime.setText(dao.getClassInfo().getSkrq());//显示上课时间
                    skxq.setText(dao.getClassInfo().getSkxq());//显示上课学期
                    break;
                //创建课堂信息提交
                case CodeConst.EXPAND_CREATE_CLASS:
                    MessageUtils.showRightImageShortToast(this, "创建成功！");
                    if (getIntent().hasExtra("result")) {
                        Intent i = new Intent();
                        i.putExtra("result", "1");
                        setResult(RESULT_OK, i);
                    }
                    finish();
                    break;
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(this, "请求数据异常");
        }
    }

    @Override
    public String setupToolBarTitle() {
        return "创建课堂";
    }

    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    @OnClick(R.id.toolbar_leftbtn)
    void onToolbarLeftClick() {
        if (getIntent().hasExtra("result")) {
            Intent i = new Intent();
            i.putExtra("result", "0");
            setResult(RESULT_OK, i);
        }
        finish();
    }

    /**
     * 适配器
     */
    private class CourseListAdapter extends AbstractWheelTextAdapter {
        List<String> list;

        protected CourseListAdapter(Context context, List<String> list, int currentItem, int maxsize, int minsize) {
            super(context, R.layout.expand_callname_courselist_item, NO_RESOURCE, currentItem, maxsize, minsize);
            this.list = list;
            setItemTextResource(R.id.tempValue);
        }


        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            TextView textView = (TextView) view.findViewById(R.id.tempValue);
            String textStr = textView.getText().toString();
            if (textStr.equals(currentText)) {
                textView.setTextSize(16);
                textView.setTextColor(getResources().getColor(R.color.color_tv333));
            } else {
                textView.setTextSize(14);
                textView.setTextColor(getResources().getColor(R.color.color_999));
            }
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }
    }

}
